package com.game.spacetrader.data;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * FusionClient.java Handles Fusion requests
 * @Version 1.0 October 31,2012
 * @author APatel
 */
public class FusionClient {
	// Databases
	private final String universedb = "1YT-g22R1WTzuR7kzw2xmo_9ip5xTWrEivL-paSg";
	private final String shipsdb = "1CrvsSDyhVjudVXQlT7gsG64uzVxv3Jun2ZIhR94";
	private final String marketdb = "17PcSp5VwHXvxLmD-tIFU52FWFYt3dKMiukyWS10";
	// Static AuthID and HostNames (DO NOT CHANGE)
	private final String AuthID = "AIzaSyAvnJcEGNVpMgT1qXO8T3hVbIhRpwydWGg";
	private final String HostTable = "https://www.googleapis.com/fusiontables/v1/tables";
	private final String HostQuery = "https://www.googleapis.com/fusiontables/v1/query";
	// Vars
	private String REQUEST_URL;

	/**
	 * Constructor, sets the Host Type
	 */
	public FusionClient() {
		REQUEST_URL = HostQuery;
	}

	/**
	 * Update -All -Forced
	 * 
	 * @param tempDB
	 *            database to update
	 */
	public String updateAF(String tempDB) {
		String retrieveDB = "";
		if (tempDB.equalsIgnoreCase("universedb"))
			retrieveDB = universedb;
		else if (tempDB.equalsIgnoreCase("shipsdb"))
			retrieveDB = shipsdb;
		else if (tempDB.equalsIgnoreCase("marketdb"))
			retrieveDB = marketdb;

		String sendQuery = "sql=SELECT+*+FROM+" + retrieveDB + "&key=" + AuthID;

		String returnQuery = sendHttpRequest(this.REQUEST_URL
				+ "?" + sendQuery, "GET");

		//TODO CALL PARSER HERE NOT IN DATA
		/*String data = FusionParse.parse(returnQuery); //debug only change to [][]
		return data;*/
		return returnQuery;
	}

	public static String sendHttpRequest(String uri, String method) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpUriRequest request;

			// Initialize the request
			if (method == "POST") {
				request = new HttpPost(uri);
				request.setHeader("Content-Type", "application/x-www-form-urlencoded");
			} else {
				request = new HttpGet(uri);
			}
			// Execute the request
			Log.d(" ",request.toString());
			HttpResponse response = httpclient.execute(request);

			// Read the response
			HttpEntity entity = response.getEntity();
			String responseContent = EntityUtils.toString(entity);

			return responseContent;

		} catch (ClientProtocolException e) {
			Log.e("error", "Incorrect protocol: " + uri, e);
		} catch (IOException e) {
			Log.e("error", "Error accessing resource: " + uri, e);
		}

		return null;
	}
}